﻿using System;
using System.Net;
using System.Text.RegularExpressions;
using Windows.UI.Xaml.Data;

namespace Unread.App.Converters
{
    /// <summary>
    /// Converts html to plain text
    /// </summary>
    public class HtmlToTextConverter : IValueConverter
    {
        /// <summary>
        /// Matches <br>, <br/>, <br />, <BR>, <br >, < br>, < br >, ...
        /// </summary>
        private static readonly Regex HtmlBreaks = new Regex(@"<[\s]*(br|BR)[\s]*[/]{0,1}[\s]*>");
        private static readonly Regex HtmlTags = new Regex("<[^>]+>");

        public object Convert(object value, Type targetType, object parameter, string language)
        {
            var originalValue = value as string;
            if (string.IsNullOrWhiteSpace(originalValue))
                return originalValue;

            var textWithNewLines = HtmlBreaks.Replace(originalValue, Environment.NewLine);
            textWithNewLines = textWithNewLines.Replace("</p>", Environment.NewLine);

            var strippedText = HtmlTags.Replace(textWithNewLines, string.Empty);
            
            return WebUtility.HtmlDecode(strippedText.Trim());
        }

        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            throw new NotImplementedException();
        }
    }
}
